<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="充电桩编号" prop="equipNo">
        <el-input
          v-model="queryParams.equipNo"
          placeholder="请输入充电桩编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="充电桩名称" prop="equipName">
        <el-input
          v-model="queryParams.equipName"
          placeholder="请输入充电桩名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:equip:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:equip:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:equip:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:equip:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="equipList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="设备ID" align="center" prop="equipId" />-->
      <el-table-column label="充电桩编号" align="center" prop="equipNo" width="120"/>
      <el-table-column label="充电桩名称" align="center" prop="equipName" width="120" />
      <el-table-column label="设备类型" align="center" prop="equipType" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.equip_type" :value="scope.row.equipType"/>
        </template>
      </el-table-column>
      <el-table-column label="插座数量" align="center" prop="channelNum" />
      <el-table-column label="所属小区" align="center" prop="areaId" width="120" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dict_area" :value="scope.row.areaId"/>
        </template>
      </el-table-column>
      <el-table-column label="网络类型" align="center" prop="networkType" />
      <el-table-column label="信号强度" align="center" prop="signalIntensity" />
      <el-table-column label="在线状态" align="center" prop="onlineStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_no" :value="scope.row.onlineStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="充电方案" align="center" prop="chargingSchemeId" width="120" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dict_charging_scheme" :value="scope.row.chargingSchemeId"/>
        </template>
      </el-table-column>
      <el-table-column label="充值方案" align="center" prop="rechargeSchemeId" width="120" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dict_recharge_scheme" :value="scope.row.rechargeSchemeId"/>
        </template>
      </el-table-column>
      <el-table-column label="设备方案" align="center" prop="equipSchemeId" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dict_equip_scheme" :value="scope.row.equipSchemeId"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:equip:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:equip:remove']"
          >删除</el-button>
          <el-button
            type="text"
            icon="el-icon-plus"
            size="mini"
            @click="exportToExcel(scope.row.equipNo,scope.row.channelNum)"
          >下载二维码</el-button>
        </template>
      </el-table-column>
      <el-table-column label="充满功率" align="center" prop="fullPower" />
      <el-table-column label="浮充时长" align="center" prop="floatTime" />
      <el-table-column label="定位LAC" align="center" prop="baseLac" />
      <el-table-column label="定位CID" align="center" prop="baseCid" />
      <el-table-column label="网络模块" align="center" prop="netModule" />
      <el-table-column label="设备类型" align="center" prop="equipModule" />
      <el-table-column label="软件版本号" align="center" prop="softNo" width="100"/>
      <el-table-column label="硬件版本号" align="center" prop="handNo" width="100"/>
      <el-table-column label="温度" align="center" prop="temp" />
      <el-table-column label="电压" align="center" prop="voltage" />
      <el-table-column label="ICCID" align="center" prop="remark" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="充电桩编号" prop="equipNo">
          <el-input v-model="form.equipNo" placeholder="请输入充电桩编号" />
        </el-form-item>
        <el-form-item label="充电桩名称" prop="equipName">
          <el-input v-model="form.equipName" placeholder="请输入充电桩名称" />
        </el-form-item>
        <el-form-item label="插座数量" prop="channelNum">
          <el-input v-model="form.channelNum" placeholder="请输入插座数量" />
        </el-form-item>
        <el-form-item label="设备类型" prop="equipType">
          <el-select v-model="form.equipType" placeholder="所在小区">
            <el-option
              v-for="dict in dict.type.equip_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在小区" prop="areaId">
          <el-select v-model="form.areaId" placeholder="所在小区">
            <el-option
              v-for="dict in dict.type.dict_area"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备方案" prop="equipSchemeId">
          <el-select v-model="form.equipSchemeId" placeholder="设备方案">
            <el-option
              v-for="dict in dict.type.dict_equip_scheme"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值方案" prop="rechargeSchemeId">
          <el-select v-model="form.rechargeSchemeId" placeholder="充值方案">
            <el-option
              v-for="dict in dict.type.dict_recharge_scheme"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充电方案" prop="chargingSchemeId">
          <el-select v-model="form.chargingSchemeId" placeholder="充电方案">
            <el-option
              v-for="dict in dict.type.dict_charging_scheme"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEquip, getEquip, delEquip, addEquip, updateEquip } from "@/api/system/equip";
import request from '@/utils/request'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
export default {
  name: "Equip",
  dicts: ['dict_area','dict_equip_scheme','dict_recharge_scheme','dict_charging_scheme','yes_no','equip_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      equipList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipNo: null,
        equipName: null,
        equipType: null,
        areaId: null,
        networkType: null,
        onlineStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        equipNo: [
          { required: true, message: "充电桩编号不能为空", trigger: "blur" }
        ],
        equipName: [
          { required: true, message: "充电桩名称不能为空", trigger: "blur" }
        ],
        equipType: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        areaId: [
          { required: true, message: "所属小区不能为空", trigger: "change" }
        ],
        channelNum: [
          { required: true, message: "插座数量", trigger: "blur" }
        ],
        equipSchemeId: [
          { required: true, message: "设备方案", trigger: "change" }
        ],
        rechargeSchemeId: [
          { required: true, message: "充值方案", trigger: "change" }
        ],
        chargingSchemeId: [
          { required: true, message: "充电方案", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listEquip(this.queryParams).then(response => {
        this.equipList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        equipId: null,
        equipNo: null,
        equipName: null,
        equipType: null,
        channelNum: null,
        areaId: null,
        networkType: null,
        signalIntensity: null,
        onlineStatus: null,
        chargingSchemeId: null,
        rechargeSchemeId: null,
        equipSchemeId: null,
        fullPower: null,
        floatTime: null,
        baseLac: null,
        baseCid: null,
        netModule: null,
        equipModule: null,
        softNo: null,
        handNo: null,
        temp: null,
        voltage: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.equipId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const equipId = row.equipId || this.ids
      getEquip(equipId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.equipId != null) {
            updateEquip(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEquip(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const equipIds = row.equipId || this.ids;
      this.$modal.confirm('是否确认删除设备管理编号为"' + equipIds + '"的数据项？').then(function() {
        return delEquip(equipIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/equip/export', {
        ...this.queryParams
      }, `equip_${new Date().getTime()}.xlsx`)
    },
    filesToRar(row) {
      const equipInfo = row
      const _this = this
      const zip = new JSZip()
      const cache = {}
      const promises = []
      let times = 1
      var setIme = setInterval(() => {
        times++
        console.log(times)
      }, 5000)
      for (let i = 0; i <= equipInfo.channelNum; i++) {
        const fileUrl = request.defaults.baseURL + '/system/equip/getEquipQR?equipNo=' + equipInfo.equipNo + '&channelNo=' + i
        const promise = _this.getImgArrayBuffer(fileUrl).then(data => {
          // 下载文件, 并存成ArrayBuffer对象(blob)
          zip.file(equipInfo.equipNo + '-' + i + '.png', data, { binary: true }) // 逐个添加文件
          cache[equipInfo.equipNo + '-' + i + '.png'] = data
        })
        promises.push(promise)
      }
      Promise.all(promises)
        .then(() => {
          zip.generateAsync({ type: 'blob' }).then(content => {
            // 生成二进制流
            FileSaver.saveAs(content, equipInfo.equipNo + '.zip') // 利用file-saver保存文件  自定义文件名
            this.$notify.close()
            this.$notify({
              message: '压缩完成'
            })
            window.clearInterval(setIme)
          })
        })
        .catch(res => {
          this.$notify({
            message: '文件压缩失败'
          })
        })
    },
    // 获取文件blob
    getImgArrayBuffer(url) {
      return new Promise((resolve, reject) => {
        const xmlhttp = new XMLHttpRequest()
        xmlhttp.open('GET', url, true)
        xmlhttp.responseType = 'blob'
        xmlhttp.onload = function() {
          // eslint-disable-next-line eqeqeq
          if (this.status == 200) {
            resolve(this.response)
          } else {
            reject(this.status)
          }
        }
        xmlhttp.send()
      })
    },
    exportToExcel(chargeNo,channelNo){
      const ws_data = []
      for (let i=0;i<=channelNo; i++){
        let data = ['http://test.kedouyun.top/ch/page/weapp/index.html#/gocharge?equipNo='+chargeNo+'&channelNo='+i,chargeNo,i]
        ws_data.push(data)
      }
      // 创建一个工作簿
      const wb = XLSX.utils.book_new();

      // 创建一个工作表
      const ws = XLSX.utils.aoa_to_sheet(ws_data);

      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      // 生成 Excel 文件
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      // 使用 FileSaver 保存文件
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < s.length; i++) {
          view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
      }

      FileSaver(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), chargeNo+'.xlsx');
    }
  }
};
</script>
